package com.ymdd.library.permission;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;

/**
 * Created by 000286 on 2017/9/22.
 * Description
 */
@RequiresApi(api = Build.VERSION_CODES.M) public class PermissionActivity extends Activity {
  static final String KEY_INPUT_PERMISSIONS = "KEY_INPUT_PERMISSIONS";

  interface RationaleListener {
    void onRationaleResult(boolean showRationale);
  }

  interface PermissionListener {
    void onRequestPermissionsResult(@NonNull String[] permissions, @NonNull int[] grantResults);
  }

  public static RationaleListener mRationaleListener;
  public static PermissionListener mPermissionListener;

  public static void setRationaleListener(RationaleListener mRationaleListener) {
    PermissionActivity.mRationaleListener = mRationaleListener;
  }

  public static void setPermissionListener(PermissionListener mRationaleListener) {
    PermissionActivity.mPermissionListener = mRationaleListener;
  }

  @RequiresApi(api = Build.VERSION_CODES.O) @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent intent = getIntent();
    String[] permissions = intent.getStringArrayExtra(KEY_INPUT_PERMISSIONS);
    if (permissions == null) {
      finish();
      return;
    }
    if (mRationaleListener != null) {
      boolean rationale = false;
      for (String permission : permissions) {
        rationale = shouldShowRequestPermissionRationale(permission);
        if (rationale) break;
      }
      mRationaleListener.onRationaleResult(rationale);
      mRationaleListener = null;
      finish();
      return;
    }
    if (mPermissionListener != null) {

      if (permissions[0].equals(PermissionArray.UNKNOWNAPK[0])) {
        //适配Android 8.0 应用申请安装权限
        ActivityCompat.requestPermissions(this, PermissionArray.UNKNOWNAPK, 1);
      } else {
        requestPermissions(permissions, 1);
      }
    }
  }

  @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
      @NonNull int[] grantResults) {
    if (requestCode == 1) {
      if (mPermissionListener != null) {
        mPermissionListener.onRequestPermissionsResult(permissions, grantResults);
      }
      mPermissionListener = null;

      finish();
    }
  }
}
